package com.appspot.moviesessions.provider;

import android.database.Cursor;
import android.net.Uri;

import com.appspot.moviesessions.provider.UriMapping.Match;

public class MovieServiceImpl implements MovieService {

	private static final String SQL_LOCATION_FOR_MOVIE = String
			.format("select distinct l.%s as %s,l.%s as %s from %s l, %s s where s.%s = l.%s and s.%s = ?",
					MovieSession.Location._ID, MovieSession.Location._ID,
					MovieSession.Location.NAME, MovieSession.Location.NAME,
					MovieSession.Location.TABLE, MovieSession.Session.TABLE,
					MovieSession.Session.LOCATION, MovieSession.Location._ID,
					MovieSession.Session.MOVIE);
	private DatabaseFactory factory;
	private UriMapping uriMapping;

	public MovieServiceImpl(DatabaseFactory databaseFactory,
			UriMapping uriMapping) {
		factory = databaseFactory;
		this.uriMapping = uriMapping;
	}

	// @Override
	// public Cursor query(QuerySpecification querySpec) {
	// return factory.getDatabase().query(querySpec);
	// }

	@Override
	public Cursor query(Uri uri, String[] projection, String where,
			String[] whereArgs, String sortOrder) {
		QuerySpecification spec = null;
		Cursor cursor = null;
		switch (uriMapping.match(uri)) {
		case MOVIE_DIRECTORY:
			spec = QuerySpecification
					.forTable(Match.MOVIE_DIRECTORY.getTable())
					.columns(projection).selection(where)
					.selectionArgs(whereArgs).sortOrder(sortOrder).build();
			cursor = factory.getDatabase().query(spec);
			break;
		case MOVIE:
			spec = QuerySpecification.forTable(Match.MOVIE.getTable())
					.columns(projection).selection("_ID = ?")
					.selectionArg(String.valueOf(uriMapping.parseId(uri)))
					.build();
			cursor = factory.getDatabase().query(spec);
			break;
		case LOCATION_DIRECTORY:
			cursor = factory.getDatabase().rawQuery(SQL_LOCATION_FOR_MOVIE,
					whereArgs);
			break;

		default:
			throw new IllegalArgumentException("Uri not matched");
		}
		return cursor;
	}
}
